Component({
  properties: {
    width: {
      type: Number,
      value: 300, // 容器宽度，单位rpx
    },
    locked: {
      type: Boolean,
      value: true,
    },
  },
  data: {
    thumbLeft: 0, // 滑块左侧距离
    thumbWidth: 150, // 滑块宽度（容器一半）
    dragging: false,
    startX: 0,
    startLeft: 0,
  },
  lifetimes: {
    attached() {
      // 初始化滑块宽度
      console.log('🐫 ~ file: index.js:21 ~ this.data.width:', this.data.width);

      this.setData({
        thumbWidth: this.data.width / 2,
        thumbLeft: 0,
      });
    },
  },
  methods: {
    onTouchStart(e) {
      if (
        (this.data.locked && this.data.thumbLeft === 0) ||
        (!this.data.locked && this.data.thumbLeft === this.data.width - this.data.thumbWidth)
      ) {
        this.setData({
          dragging: true,
          startX: e.touches[0].clientX,
          startLeft: this.data.thumbLeft,
        });
      }
    },
    onTouchMove(e) {
      if (!this.data.dragging) return;
      const moveX = e.touches[0].clientX - this.data.startX;
      let newLeft = this.data.startLeft + moveX;
      // 限制滑块范围
      newLeft = Math.max(0, Math.min(this.data.width - this.data.thumbWidth, newLeft));
      this.setData({
        thumbLeft: newLeft,
      });
    },
    onTouchEnd() {
      if (!this.data.dragging) return;
      const half = (this.data.width - this.data.thumbWidth) / 2;
      let locked = true;
      let thumbLeft = 0;
      // 判断吸附到哪一端
      if (this.data.thumbLeft > half) {
        locked = false;
        thumbLeft = this.data.width - this.data.thumbWidth;
      }
      this.setData({
        locked,
        thumbLeft,
        dragging: false,
      });
      // 触发事件
      this.triggerEvent(locked ? 'lock' : 'unlock');
    },
  },
});
